import Vue from 'vue'
import Vuex from 'vuex'
import mvvm from '../main'
// import router from '../router'
// import { userFrozenTips } from '../utils/common'
// import { apiPost, CTS } from '../utils/http'
// import router, { resetRouter } from '../router'

Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// 自动加载所有vuex模块
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

// state 中需要缓存在 localStorage 的属性
const localKey = []

// state 中需要缓存在 sessionStorage 的属性
const sessionKey = [
  'userInfo',
  'user/token',
  'user/id',
  'user/username',
  'user/nickname',
  'user/roles',
  'user/permissions',
]

export default new Vuex.Store({
  state: {
    is_init: false, // 是否初始化完成
  },
  modules,
  getters: {
    // 是否登录
    is_login: (state) => {
      return Boolean(state.user.token)
    },

    token: state => state.user.token,
    avatar: state => state.user.avatar,
    name: state => state.user.name,
    roles: (state) => {
      // 用户的角色，0 (未登录)游客 1 超级管理 3 销售经理 5 贵宾用户 7 普通用户
      return ['tourist', 'admin', 2, 'manager', 4, 'vip', 6, 'login'][Number(state.user.role)]
    },

    sidebar: state => state.app.sidebar,
    // 菜单
    permission_routes: state => state.permission.routes,

    size: state => state.app.size,
    device: state => state.app.device,
    visitedViews: state => state.tagsView.visitedViews,
    cachedViews: state => state.tagsView.cachedViews,
    introduction: state => state.user.introduction,

    errorLogs: state => state.errorLog.logs
  },
  mutations: {
    /**
     * 设置 state 中的部分数据，注意，模块内属性设置，需要加上模块名，以 / 间隔，如 user/name
     * @param data [object] 要设置的数据，以 json 格式传入
     * */
    setStateData(state, data) {
      for (let key in data) {
        setState(state, key, data[key])

        let s = JSON.stringify({
          v: data[key],
          d: Date.now(),
          t: typeof data[key],
        })

        if (localKey.includes(key)) {
          localStorage.setItem(key, s)
        } else if (sessionKey.includes(key)) {
          sessionStorage.setItem(key, s)
        }
      }
    },
    setMduleStateData(state, options) {
      let module = options.module || ''
      let data = options.data || {}
      let dat2 = {}
      for (let key in data) {
        dat2[module + '/' + key] = data[key]
      }
      mvvm.$store.commit('setStateData', dat2)
    },
  },
  actions: {
    /**
     * 应用初始化，在这里获取缓存的数据以及其它的准备工作
     *
     * */
    appInit({ state, dispatch }) {
      initCacheStateData(state)

      // dispatch('user/updateUserInfo').then(() => {
      //   dispatch('user/login')
      // }).catch(err => {
      //   console.log(err);
      // })

      state.init = true
    },
    /*
    * 退出登录
    * */
    logout({ state }) {
      localKey.forEach(key => {
        state[key] = ''
        localStorage.removeItem(key)
      })

      sessionKey.forEach(key => {
        state[key] = ''
        sessionStorage.removeItem(key)
      })
    },
  }
})


/**
 * 设置 state
 *
 * */
const setState = (state, key, value) => {
  let a = key.split('/')
  let s = state

  for (let i = 0; i < a.length; i++) {
    if (i === a.length - 1) {
      s[a[i]] = value
    } else {
      s = s[a[i]]
    }
  }
}


/**
 * 初始化，获取本地缓存的数据到 state
 * */
const initCacheStateData = (state) => {
  localKey.forEach(key => {
    try {
      if (localStorage.getItem(key) !== null) {
        let s = localStorage.getItem(key)
        let data = JSON.parse(s)

        if (data.t && data.d) {
          setState(state, key, data.v)
        } else {
          localStorage.removeItem(key)
        }
      }
    } catch (e) {
      localStorage.removeItem(key)
    }
  })

  sessionKey.forEach(key => {
    try {
      if (sessionStorage.getItem(key) !== null) {
        let s = sessionStorage.getItem(key)
        let data = JSON.parse(s)

        if (data.t && data.d) {
          setState(state, key, data.v)
        } else {
          sessionStorage.removeItem(key)
        }
      }
    } catch (e) {
      console.log(e);
      sessionStorage.removeItem(key)
    }
  })
}
